package com.example.pceb.controller;

import com.example.pceb.VO.ApplyInformationVO;
import com.example.pceb.entity.*;
import com.example.pceb.result.Result;
import com.example.pceb.service.AdminService;
import com.example.pceb.service.RecruitService;
import com.sun.tools.jconsole.JConsoleContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.Map;
import com.example.pceb.service.UserService;
import com.example.pceb.service.EnterpriseService;
import com.example.pceb.service.SchoolService;

@RestController
@RequestMapping("/admins")
//@CrossOrigin(origins = "*")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RecruitService recruitService;
    @Autowired
    private UserService userService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private SchoolService schoolService;
    @GetMapping("all")
    public Result<List<Information>> getAll() {
        return adminService.getAllInformation();
    }
    @GetMapping("Policy")
    public Result<List<Information>> getPolicy() {
        return adminService.getPolicy();
    }
    @GetMapping("Business")
    public Result<List<Information>> getBusiness() {
        return adminService.getBusiness();
    }
    @GetMapping("Recruit")
    public Result<List<Information>> getRecruit() {
        return adminService.getRecruit();
    }
    @GetMapping("Cooperation")
    public Result<List<Information>> getCooperation() {
        return adminService.getCooperation();
    }
    @GetMapping("School")
    public Result<List<School>> getSchool() {
        return adminService.getSchool();
    }
    @GetMapping("Enterprise")
    public Result<List<Enterprise>> getEnterprise() {
        return adminService.getEnterprise();
    }
    @GetMapping("Examine")
    public Result<List<ApplyInformationVO>> getExamine() {
        return adminService.getExamine();
    }
    @DeleteMapping("delExamine")
    public Result<String> delExamine(@RequestBody List<Integer> idList) {
        return adminService.delExamine(idList);
    }
    @PutMapping("updateExamine")
    public Result<String> updateExamine(Integer id,Integer isPass) {
        return adminService.qualifiedExamine(id,isPass);
    }
    @PutMapping("addInformation")
    public Result<String> addInformation(@RequestBody Information information) {
        return adminService.addInformation(information);
    }
    @PutMapping("updateInformation")
    public Result<String> updateInformation(@RequestBody Information information) {
        return adminService.updateInformation(information);
    }
    @DeleteMapping("delInformation")
    public Result<String> delInformation(@RequestBody List<Integer> idList) {
        return adminService.delInformation(idList);
    }

    @PutMapping("addStudent")
    public Result<String> addStudent(@RequestBody Student student) {
        return adminService.addStudent(student);
    }
    @PutMapping("updateStudent")
    public Result<String> updateStudent(@RequestBody Student student) {
        return adminService.updateStudent(student);
    }
    @DeleteMapping("delStudent")
    public Result<String> delStudent(@RequestBody List<String> idList) {
        return adminService.delStudent(idList);
    }

    @PutMapping("addEnterprise")
    public Result<String> addEnterprise(@RequestBody Enterprise enterprise) {
        return adminService.addEnterprise(enterprise);
    }
    @PutMapping("updateEnterprise")
    public Result<String> updateEnterprise(@RequestBody Enterprise enterprise) {
        return adminService.updateEnterprise(enterprise);
    }
    @DeleteMapping("delEnterprise")
    public Result<String> delEnterprise(@RequestBody List<String> idList) {
        return adminService.delEnterprise(idList);
    }

    @PutMapping("addSchool")
    public Result<String> addSchool(@RequestBody School school) {

        return adminService.addSchool(school);
    }
    @PutMapping("updateSchool")
    public Result<String> updateSchool(@RequestBody School school) {
        return adminService.updateSchool(school);
    }
    @DeleteMapping("delSchool")
    public Result<String> delSchool(@RequestBody List<Integer> idList) {
        return adminService.delSchool(idList);
    }
    @GetMapping("Questions")
    public Result<List<QueBank>> getQuestions() {
        return adminService.getAllQuestionBank();
    }

    @PostMapping("upload")
    public Result<String> upload(@RequestParam("file") MultipartFile multipartFile) {
        try {
            System.out.println("开始处理文件上传");
            System.out.println("文件名: " + multipartFile.getOriginalFilename());
            System.out.println("文件大小: " + multipartFile.getSize() + " bytes");
            System.out.println("文件类型: " + multipartFile.getContentType());

            // 检查文件是否为空
            if (multipartFile.isEmpty()) {
                System.out.println("文件为空");
                return Result.error("文件不能为空");
            }

            // 检查文件大小（限制为10MB）
            if (multipartFile.getSize() > 10 * 1024 * 1024) {
                System.out.println("文件过大: " + multipartFile.getSize() + " bytes");
                return Result.error("文件大小不能超过10MB");
            }

            // 使用指定的绝对路径作为上传目录
            String uploadDir = "D:\\成都实训项目\\school-enterprise-alliance\\src\\main\\resources\\uploads";
            File dir = new File(uploadDir);
            System.out.println("上传目录: " + dir.getAbsolutePath());

            // 确保目录存在
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                if (!created) {
                    System.out.println("创建上传目录失败");
                    return Result.error("创建上传目录失败");
                }
                System.out.println("创建上传目录成功");
            }

            // 生成唯一文件名
            String originalFilename = multipartFile.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String uniqueFilename = System.currentTimeMillis() + "_" + (int)(Math.random() * 1000) + fileExtension;
            System.out.println("生成的文件名: " + uniqueFilename);

            // 创建目标文件
            File dest = new File(dir.getAbsolutePath() + "\\" + uniqueFilename);
            System.out.println("目标文件路径: " + dest.getAbsolutePath());

            // 复制文件
            FileCopyUtils.copy(multipartFile.getBytes(), dest);
            System.out.println("文件复制成功");

            // 验证文件是否成功保存
            if (!dest.exists()) {
                System.out.println("文件保存失败，文件不存在");
                return Result.error("文件保存失败");
            }

            // 返回文件路径（相对路径，用于数据库存储）
            String filePath = "/uploads/" + uniqueFilename;
            System.out.println("返回文件路径: " + filePath);
            return Result.success(filePath);

        } catch (IOException e) {
            System.err.println("文件上传异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("未知异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }

    @GetMapping("download")
    public ResponseEntity<Resource> download(@RequestParam("filePath") String filePath) throws IOException {
        try {
            System.out.println("开始下载文件: " + filePath);

            // 从文件路径中提取文件名
            String filename = filePath.substring(filePath.lastIndexOf("/") + 1);
            System.out.println("文件名: " + filename);

            // 构建绝对文件路径
            String absolutePath = "D:\\成都实训项目\\school-enterprise-alliance\\src\\main\\resources\\uploads\\" + filename;
            File file = new File(absolutePath);
            System.out.println("绝对文件路径: " + absolutePath);

            if (!file.exists()) {
                System.out.println("文件不存在: " + absolutePath);
                return ResponseEntity.notFound().build();
            }

            // 创建文件资源
            Resource resource = new org.springframework.core.io.FileSystemResource(file);

            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=\"" + filename + "\"")
                    .body(resource);

        } catch (Exception e) {
            System.err.println("文件下载异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 管理员头像上传接口
     */
    @PostMapping("uploadAvatar")
    public Result<?> uploadAvatar(@RequestParam("file") MultipartFile file, @RequestParam("adminId") Integer adminId) {
        if (file.isEmpty()) {
            return Result.error("文件不能为空");
        }
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;
        // 保存路径
        String uploadDir = "D:/成都实训项目/school-enterprise-alliance/src/main/resources/uploads/avatar/";
        File dir = new File(uploadDir);
        if (!dir.exists()) dir.mkdirs();
        File dest = new File(uploadDir + fileName);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            return Result.error("文件保存失败");
        }
        // 数据库存相对路径
        String avatarUrl = "/uploads/avatar/" + fileName;
        Result<String> updateResult = adminService.updateAdminAvatar(adminId, avatarUrl);
        if (updateResult.getCode() != 200) {
            return Result.error("数据库更新头像失败");
        }
        return Result.success(avatarUrl);
    }


    //获取职位所有信息
    // 获取所有职位（管理员用）
    @GetMapping("recruits/all")
    public Result<List<Recruit>> adminAll() {
        List<Recruit> list = recruitService.list();
        return Result.success(list);
    }

    // 审核职位
    @PostMapping("recruits/audit")
    public Result<?> auditRecruit(@RequestBody Map<String, Object> params) {
        Integer id = (Integer) params.get("id");
        Integer status = (Integer) params.get("status"); // 1通过 2拒绝
        if (id == null || status == null) return Result.error("参数错误");
        Recruit recruit = recruitService.getById(id);
        if (recruit == null) return Result.error("职位不存在");
        recruit.setIsPass(status);
        recruitService.updateById(recruit);
        return Result.success();
    }

    // 设置/取消热门
    @PostMapping("recruits/hot")
    public Result<?> setHot(@RequestBody Map<String, Object> params) {
        Integer id = (Integer) params.get("id");
        Integer isHot = (Integer) params.get("isHot"); // 1热门 0不热门
        if (id == null || isHot == null) return Result.error("参数错误");
        Recruit recruit = recruitService.getById(id);
        if (recruit == null) return Result.error("职位不存在");
        recruit.setIsHot(isHot);
        recruitService.updateById(recruit);
        return Result.success();
    }

    @GetMapping("platformStats")
    public Result<Map<String, Integer>> getPlatformStats() {
        Map<String, Integer> stats = new java.util.HashMap<>();
        stats.put("userTotal", userService.countAllUsers());
        stats.put("companyTotal", enterpriseService.countAllEnterprises());
        stats.put("schoolTotal", schoolService.countAllSchools());
        return Result.success(stats);
    }

    @GetMapping("userTypeStats")
    public Result<java.util.List<java.util.Map<String, Object>>> getUserTypeStats() {
        return Result.success(userService.countUserByIdentity());
    }
}
